<template>
  <div class="editor-container" style="width: 210mm; height: 297mm;margin: 0 auto;">
    <quill-editor class="custom-editor" content-type="html" :content="content" :options="dynamicOptions" />
  </div>
</template>

<script setup>
import { QuillEditor } from '@vueup/vue-quill';
import { marked } from 'marked';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import { ref, watch, computed, defineProps } from 'vue';

const props = defineProps({
  value: {
    type: String,
    default: "<p>初始内容...</p>"
  },
  fontSize: {
    type: String,
    default: "12"
  },
  indentation: {
    type: String,
    default: "0"
  },
  headingSize: {
    type: String,
    default: "24"
  },
  lineHeight: {
    type: String,
    default: "1"
  }
});

const dynamicOptions = computed(() => ({
  modules: {
    toolbar: [
      // 保持原有的工具栏配置
      ['bold', 'italic', 'underline', 'strike'],
      [{ color: [] }, { background: [] }],
      [{ align: [] }],
      [{ size: ['small', 'large', 'huge'] }],
      [{ font: [] }],
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      [{ direction: 'ltl' }, { direction: 'rtl' }],
      [{ indent: '-1' }, { indent: '+1' }],
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }],
      ['blockquote', 'code-block'],
      ['clean'],
      ['link', 'image', 'video']
    ]
  }
}));

// 样式处理函数
const processHtmlStyles = (html) => {
  try {
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');

    const applyStyles = (element) => {
      const tagName = element.tagName.toLowerCase();
      const styles = {};

      // 设置段落样式
      if (tagName === 'p') {
        styles['font-size'] = `${props.fontSize}px`;
        styles['text-indent'] = `${props.indentation}px`;
        styles['line-height'] = props.lineHeight;
      }
      // 设置标题样式
      else if (/^h[1-6]$/.test(tagName)) {
        styles['font-size'] = `${props.headingSize}px`;
        styles['line-height'] = props.lineHeight;
      }

      // 合并原有样式
      const existingStyles = element.getAttribute('style') || '';
      const styleObject = existingStyles
        .split(';')
        .filter(s => s)
        .reduce((acc, cur) => {
          const [key, value] = cur.split(':').map(s => s.trim());
          if (key) acc[key] = value;
          return acc;
        }, {});

      // 应用新样式（覆盖原有）
      Object.assign(styleObject, styles);

      // 转换为样式字符串
      const styleString = Object.entries(styleObject)
        .map(([key, value]) => `${key}:${value}`)
        .join(';');

      element.setAttribute('style', styleString);
    };

    // 递归遍历所有节点
    const walkNodes = (nodes) => {
      nodes.forEach(node => {
        if (node.nodeType === Node.ELEMENT_NODE) {
          applyStyles(node);
          if (node.children.length > 0) {
            walkNodes([...node.children]);
          }
        }
      });
    };

    walkNodes([...doc.body.children]);
    return doc.body.innerHTML;
  } catch (error) {
    console.error('HTML processing error:', error);
    return html;
  }
};

// 处理后的内容
const processedContent = ref('');
const content = ref('');
// 监听内容和样式参数变化
watch(() => [props.value, props.fontSize, props.indentation, props.headingSize, props.lineHeight],
  ([newValue]) => {
    try {
      // 转换Markdown为HTML
      const rawHtml = marked(newValue);
      // 应用样式处理
      const styledHtml = processHtmlStyles(rawHtml);
      processedContent.value = styledHtml;
      content.value = styledHtml;
      console.log(processedContent.value)
    } catch (e) {
      console.error('Content processing failed:', e);
      processedContent.value = newValue;
    }
  }
);

</script>